﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using System.Timers;
using System.Windows;
using System.Windows.Threading;
using CoreAudioApi;
using Swan.WakeUpLibrary.Library;

namespace Swan.SwanWakeUp.AlarmActions
{
    public class DefaultAction
    {
        Timer timer;
        MP3Player player;
        static int volume = 0;
        private MMDevice device;

        internal void Run()
        {
            //Master volume
            MMDeviceEnumerator devEnum = new MMDeviceEnumerator();
            device = devEnum.GetDefaultAudioEndpoint(EDataFlow.eRender, ERole.eMultimedia);


            //timer.Tick+=new EventHandler(timer_Tick);
            //timer.Interval = 1000;

            this.RunSpeach();

            player = new MP3Player();
            string path;
            if (Properties.Settings.Default.UseCustomSong && File.Exists(Properties.Settings.Default.CustomSongPath))
            {
                path = Properties.Settings.Default.CustomSongPath;
            }
            else
            {
                path = AppDomain.CurrentDomain.BaseDirectory + "\\media\\DefaultAlarm.mp3";
            }

            try
            {
                player.OpenMediaFile(path);

                timer = new Timer(4000);//4000 ger typ 400sek vilket ger ca 6 min wakeuptime
                timer.Interval = 4000;
                timer.BeginInit();
                timer.Elapsed += new ElapsedEventHandler(timer_Elapsed);
                timer.AutoReset = true;
                timer.InitializeLifetimeService();

                timer.EndInit();
                timer.Enabled = true;
                MP3Player.waveOutSetVolume(0, (uint)volume);
                device.AudioEndpointVolume.MasterVolumeLevelScalar = 0;
                player.PlayMediaFile(true);
                timer.Start();
            }
            catch (Exception ex)
            {
                EventLog.WriteEntry(Assembly.GetEntryAssembly().FullName, "Could not play song in alarm, ex: " + ex.Message, EventLogEntryType.Warning);
            }
            
            Dispatcher.CurrentDispatcher.BeginInvoke(new Action(() =>
                {
                    try
                    {
                    MessageBoxResult res = MessageBox.Show("Good morning sunshine, turn of the alarm?", "Good morning", MessageBoxButton.YesNo);
                    if (res == MessageBoxResult.Yes)
                        Application.Current.Shutdown();
                    }           
                    catch (Exception ex)
                    {
                        EventLog.WriteEntry(Assembly.GetEntryAssembly().FullName, "Could not display GUI: " + ex.Message, EventLogEntryType.Warning);
                    }
                }), null);
        }

        bool noMoreSpeech = false;

        private void RunSpeach()
        {
            var speech = new TextToSpeechAction();

            try
            {
                device.AudioEndpointVolume.MasterVolumeLevelScalar = 1;
                Swan.WakeUpLibrary.Library.MP3Player.waveOutSetVolume(0, (uint.MaxValue));

                //TODO this is a temporary test
                speech.Speech("Time " + DateTime.Now.ToString("HH:mm"));
                speech.Speech("Time to wake up.");
                speech.Speech("The time is now " + DateTime.Now.ToString("HH:mm"));

                var weather = new YrWeatherAction();
                var cond = weather.GetCurrentConditions("Stockholm");
                if (cond != null)
                {
                    speech.Speech("The temperature for " + cond.City + " is " + cond.TempC + " degrees." + cond.Humidity);
                    speech.Speech(" The wind is a " + cond.Wind + " from " + cond.WindDir + ".");
                    speech.Speech("The sky is " + cond.Condition + ".");

                }


                System.Threading.Thread.Sleep(5000);
            }
            catch (Exception) { }
        }

        void timer_Elapsed(object sender, ElapsedEventArgs e)
        {
            if (volume != 100)
            {
                volume++;
                MP3Player.waveOutSetVolume(0, (uint)((double)volume * 650));
                device.AudioEndpointVolume.MasterVolumeLevelScalar = ((float)((double)volume / 100));
            }
            else if(!noMoreSpeech)
            {
                noMoreSpeech = true;
                this.RunSpeach();
            }
        }
    }
}
